package ynu.edu.online_course.mapper;

import org.apache.ibatis.annotations.*;
import ynu.edu.online_course.entity.Chapter;
import java.util.List;

@Mapper
public interface ChapterMapper {

    // 根据课程ID查询章节列表
    @Select("SELECT * FROM chapter WHERE course_id = #{courseId}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "chapterName", column = "chapter_name"),
            @Result(property = "course.id", column = "course_id"),
            @Result(property = "parentChapter", column = "parent_id",
                    one = @One(select = "ynu.edu.online_course.mapper.ChapterMapper.findById")),
            @Result(property = "childChapters", column = "id",
                    many = @Many(select = "ynu.edu.online_course.mapper.ChapterMapper.findSubChapters"))
    })
    List<Chapter> findByCourseId(@Param("courseId") Long courseId);


    // 插入章节
    @Insert("INSERT INTO chapter (course_id, chapter_name, parent_id) " +
            "VALUES (#{course.id}, #{chapterName}, #{parentId})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertChapter(Chapter chapter);

    // 更新章节
    @Update("UPDATE chapter SET chapter_name = #{chapterName} WHERE id = #{id}")
    int updateChapter(Chapter chapter);

    // 查询子章节
    @Select("SELECT * FROM chapter WHERE parent_id = #{parentId}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "chapterName", column = "chapter_name"),
            @Result(property = "course.id", column = "course_id"),
            @Result(property = "parentChapter", column = "parent_id",
                    one = @One(select = "ynu.edu.online_course.mapper.ChapterMapper.findById"))
    })
    List<Chapter> findSubChapters(@Param("parentId") Long parentId);

    @Select("SELECT * FROM chapter WHERE id = #{id}")
    Chapter findById(@Param("id") Long id);

}
